"use client"

import { Platform, View, Text, TouchableOpacity, StyleSheet, ScrollView } from "react-native"
import { useState, useCallback, useEffect, useRef } from "react"
import { theme } from "../../constants/theme"
import { WordStatusBar } from "./WordStatusBar"
import { VideoModal } from "./VideoModal"
import { PracticalExamples } from "./PracticalExamples"
import { WordEtymology } from "./WordEtymology"
import { NaturalReading } from "./NaturalReading"
import { SyllableSplitting } from "./SyllableSplitting"
import { useRouter } from "expo-router"

interface WordCardContentProps {
    word: {
        id: string
        word: string
        phonetic: string
        type: string
        meanings: string[]
        syllables: string[]
        phoneticSyllables: string[]
        examples: Array<{ en: string; cn: string }>
        status: "new" | "learning" | "mastered"
        favorite: boolean
        etymology?: {
            parts: Array<{
                text: string
                meaning: string
            }>
            explanation: string
        }
        naturalReadingData?: {
            letter: string
            phonetic: string
            color?: string
        }[]
    }
    isPlaying: boolean
    isSlowPlaying: boolean
    isRecording: boolean
    onPlayAudio: (slow?: boolean) => void
    onRecord: () => void
    onUpdateStatus: (status: "new" | "learning" | "mastered") => void
    onToggleFavorite: () => void
    settings: {
        translationFontSize: number
        moduleFontSize: number
    }
}

// 扩展示例数据，添加更多实用口语
const ADDITIONAL_EXAMPLES = [
    {
        en: "This is a practical example of the word.",
        cn: "这是该单词的一个实用例子。",
    },
    {
        en: "Let me show you how to use this word.",
        cn: "让我向你展示如何使用这个单词。",
    },
    {
        en: "You can practice with this sentence.",
        cn: "你可以用这个句子练习。",
    },
]

export function WordCardContent({
    word,
    isPlaying,
    isSlowPlaying,
    isRecording,
    onPlayAudio,
    onRecord,
    onUpdateStatus,
    onToggleFavorite,
    settings,
    hideStatusBar,
}: WordCardContentProps) {
    const router = useRouter()
    // 添加拆分状态
    const [isSplit, setIsSplit] = useState(true) // 默认显示拆分状态
    const [selectedPhonetic, setSelectedPhonetic] = useState<number | null>(null)
    const [isPlayingPart, setIsPlayingPart] = useState<string | null>(null)
    const [isPlayingSequence, setIsPlayingSequence] = useState(false)
    const [activeButton, setActiveButton] = useState<"split" | "natural">("split") // 默认选中拆分发音

    // 视频模态框状态
    const [videoModalVisible, setVideoModalVisible] = useState(false)
    const [selectedPhoneticForVideo, setSelectedPhoneticForVideo] = useState<string>("")

    // 合并原始例子和额外例子
    const allExamples = [...(word.examples || []), ...ADDITIONAL_EXAMPLES]

    // 模拟播放音频
    const playAudio = useCallback(async (text: string, duration = 1000) => {
        setIsPlayingPart(text)
        console.log(`播放音频: ${text}`)

        // Simulate different durations based on text length
        const calculatedDuration = Math.max(500, text.length * 200)

        return new Promise<void>((resolve) => {
            setTimeout(() => {
                setIsPlayingPart(null)
                resolve()
            }, duration || calculatedDuration)
        })
    }, [])

    // 播放完整单词然后播放拆分部分
    const playFullThenSplit = useCallback(async () => {
        if (isPlayingSequence) return

        // 重置滚动位置
        if (scrollViewRef.current) {
            scrollViewRef.current.scrollTo({ x: 0, y: 0, animated: false })
        }

        setIsPlayingSequence(true)

        // 先合并显示
        setIsSplit(false)

        // 播放完整单词
        await playAudio(word.word, 1200)

        // 等待一小段时间
        await new Promise((resolve) => setTimeout(resolve, 300))

        // 显示拆分状态，但不再依次播放各部分
        setIsSplit(true)

        setIsPlayingSequence(false)
    }, [playAudio, word, isPlayingSequence])

    // 处理拆分发音按钮点击
    const handleSplitButtonPress = () => {
        setActiveButton("split")
        playFullThenSplit()
    }

    // 处理自然拼读按钮点击
    const handleNaturalButtonPress = () => {
        setActiveButton("natural")
        setIsSplit(false)
        setIsPlayingPart(null)
        setIsPlayingSequence(false)
    }

    // 处理单词部分点击
    const handleSyllablePress = (syllable: string, index: number) => {
        playAudio(syllable)
    }

    // 处理音标点击
    const handlePhoneticPress = (phonetic: string, index: number) => {
        setSelectedPhonetic(index)
        playAudio(phonetic)
    }

    // 处理视频按钮点击
    const handleVideoPress = () => {
        if (selectedPhonetic !== null) {
            setSelectedPhoneticForVideo(word.phoneticSyllables[selectedPhonetic])
            setVideoModalVisible(true)
        } else {
            // 如果没有选中音标，默认显示第一个
            setSelectedPhoneticForVideo(word.phoneticSyllables[0] || "/ə/")
            setVideoModalVisible(true)
        }
    }

    // 处理详解按钮点击
    const handleDetailPress = () => {
        console.log("详解按钮点击 - 单词:", word.word)
        // 导航到详情页面
        router.push(`/word-detail-screen?word=${word.word}`)
    }

    const scrollViewRef = useRef<ScrollView>(null)

    // 修改 useEffect 钩子，确保在 word.id 变化时立即重置滚动位置，使用 animated: false 确保立即生效
    useEffect(() => {
        if (scrollViewRef.current) {
            // 使用 animated: false 确保立即重置，不使用动画
            scrollViewRef.current.scrollTo({ x: 0, y: 0, animated: false })
        }
    }, [word.id])

    useEffect(() => {
        // 当单词变化时自动播放
        // 确保每次切换单词时，始终是音节拆分模式
        setActiveButton("split")

        // 重置状态，防止在切换单词时出现问题
        setIsPlayingPart(null)
        setIsPlayingSequence(false)
        setSelectedPhonetic(null)

        // 延迟一帧后再播放，确保状态已更新
        setTimeout(() => {
            playFullThenSplit()
        }, 0)

        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [word.id]) // 只在单词ID变化时触发

    return (
        <View style={[styles.wordCard,hideStatusBar && styles.wordCardMargin]}>
            <ScrollView ref={scrollViewRef} style={styles.scrollContent} showsVerticalScrollIndicator={false}>
                {/* 单词状态栏 */}
                <View style={styles.cardHeader}>
                    <View style={styles.segmentedControlContainer}>
                        <View style={styles.segmentedControl}>
                            <TouchableOpacity
                                style={[
                                    styles.segmentButton,
                                    styles.segmentButtonLeft,
                                    activeButton === "split" && styles.segmentButtonActive,
                                ]}
                                onPress={handleSplitButtonPress}
                                disabled={isPlayingSequence}
                            >
                                <Text style={[styles.segmentButtonText, activeButton === "split" && styles.segmentButtonTextActive]}>
                                    音节拆分
                                </Text>
                            </TouchableOpacity>

                            <TouchableOpacity
                                style={[
                                    styles.segmentButton,
                                    styles.segmentButtonRight,
                                    activeButton === "natural" && styles.segmentButtonActive,
                                ]}
                                onPress={handleNaturalButtonPress}
                            >
                                <Text style={[styles.segmentButtonText, activeButton === "natural" && styles.segmentButtonTextActive]}>
                                    自然拼读
                                </Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>

                {activeButton === "natural" ? (
                    <NaturalReading
                        word={word.word}
                        phoneticUnits={word.naturalReadingData || []}
                        onPlayAudio={playAudio}
                        isPlayingPart={isPlayingPart}
                        translation={word.meanings.join("；")}
                        type={word.type}
                        settings={settings}
                    />
                ) : (
                    // 音节拆分模式下显示所有内容
                    <>
                        <SyllableSplitting
                            word={word}
                            isPlayingPart={isPlayingPart}
                            selectedPhonetic={selectedPhonetic}
                            isSplit={isSplit}
                            settings={settings}
                            onPlayAudio={playAudio}
                            onSyllablePress={handleSyllablePress}
                            onPhoneticPress={handlePhoneticPress}
                            onVideoPress={handleVideoPress}
                            DetailPress={handleDetailPress}

                        />

                        {/* 词根助记部分 */}
                        {word.etymology?.parts?.length && (
                            <WordEtymology etymology={word.etymology} fontSize={settings.moduleFontSize} />
                        )}

                        {/* 实用口语部分 */}
                        <PracticalExamples
                            examples={allExamples}
                            isPlaying={isPlaying}
                            isRecording={isRecording}
                            onPlayAudio={onPlayAudio}
                            onRecord={onRecord}
                            wordId={word.id}
                            fontSize={settings.moduleFontSize}
                        />
                    </>
                )}

                <View style={styles.bottomPadding} />
            </ScrollView>

            {/* 固定在底部的状态栏 */}
            {
                !hideStatusBar && <View style={styles.fixedBottomContainer}>
                    <WordStatusBar
                        currentStatus={word.status}
                        isFavorite={word.favorite}
                        onUpdateStatus={onUpdateStatus}
                        onToggleFavorite={onToggleFavorite}
                    />
                </View>
            }


            {/* 视频播放模态框 */}
            <VideoModal
                visible={videoModalVisible}
                onClose={() => setVideoModalVisible(false)}
                phoneticSymbol={selectedPhoneticForVideo}
            />
        </View>
    )
}

const styles = StyleSheet.create({
    wordCard: {
        flex: 1,
        backgroundColor: theme.colors.neutral.white,
        borderRadius: theme.borderRadius.extraLarge,
        margin: theme.spacing.lg,
        marginBottom: theme.spacing.xl, // 增加底部外边距，与底部导航保持更多距离
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowOffset: { width: 0, height: 4 },
                shadowOpacity: 0.5,
                shadowRadius: 8,
            },
            android: {
                elevation: 4,
            },
        }),
        position: "relative",
    },
    wordCardMargin:{
        margin: 10,
        marginBottom: 0, // 增加底部外边距，与底部导航保持更多距离
        marginTop: 0, // 增加底部外边距，与底部导航保持更多距离
    },
    scrollContent: {
        flex: 1,
        padding: theme.spacing.xl,
        paddingBottom: theme.spacing.xl, // 增加底部内边距，为固定按钮和状态栏留出空间
    },
    bottomPadding: {
        height: 60, // 减小底部填充的高度
    },
    fixedBottomContainer: {
        position: "absolute",
        bottom: 0,
        left: 0,
        right: 0,
        backgroundColor: theme.colors.neutral.white,
        borderBottomLeftRadius: theme.borderRadius.extraLarge,
        borderBottomRightRadius: theme.borderRadius.extraLarge,
        padding: theme.spacing.md,
    },
    cardHeader: {
        paddingHorizontal: theme.spacing.lg,
        paddingBottom: theme.spacing.md,
        marginBottom: theme.spacing.md,
    },
    segmentedControlContainer: {
        marginBottom: theme.spacing.sm,
    },
    segmentedControl: {
        flexDirection: "row",
        backgroundColor: "rgba(0, 0, 0, 0.05)",
        borderRadius: theme.borderRadius.large,
        padding: 3,
        height: 36,
    },
    segmentButton: {
        flex: 1,
        alignItems: "center",
        justifyContent: "center",
        borderRadius: theme.borderRadius.medium,
    },
    segmentButtonLeft: {
        marginRight: 1,
    },
    segmentButtonRight: {
        marginLeft: 1,
    },
    segmentButtonActive: {
        backgroundColor: theme.colors.primary.default,
    },
    segmentButtonText: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.darkGray,
        fontWeight: theme.fontWeight.medium,
    },
    segmentButtonTextActive: {
        color: theme.colors.neutral.white,
        fontWeight: theme.fontWeight.semiBold,
    },
})

